import time

import jwt
from flask import jsonify, Blueprint, request
from flask_restful import Api, Resource, reqparse

from models.model import *
from utils.my_route import route_code

user_bp = Blueprint('user_bp', __name__)
api = Api(user_bp)
secret = 'shgfksnflslfldsfj'


class UserView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('username', required=True)
        req.add_argument('password', required=True)
        req.add_argument('name', required=True)
        args = req.parse_args()
        user_one = User.query.filter(User.username == args['username']).first()
        if user_one:
            return jsonify({
                'code': 200,
                'msg': '账号已经存在'
            })
        try:
            user_info = User(username=args['username'], password=args['password'], name=args['name'])
            db.session.add(user_info)
            db.session.commit()
            return jsonify({
                'code': 200,
                'msg': '注册成功'
            })
        except:
            return jsonify({
                'code': 400,
                'msg': '注册失败'
            })


class UserLoginView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('username', required=True)
        req.add_argument('password', required=True)
        args = req.parse_args()
        user_info = User.query.filter(User.username == args['username']).first()
        if not user_info:
            return jsonify({
                'code': 400,
                'msg': '用户不存在'
            })
        if not user_info.password == args['password']:
            return jsonify({
                'code': 400,
                'msg': '密码错误'
            })
        payload = {
            'id': user_info.id,
            'name': user_info.name,
            'username': user_info.username,
            'exp': int(time.time()) + 2 * 3600
        }
        token = jwt.encode(payload, key=secret, algorithm="HS256")

        return jsonify({
            'code': 200,
            'msg': '登录成功',
            "token": token,
        })


class UserGetView(Resource):
    def get(self):
        token = request.headers.get("authorization", None)
        if token:
            data = jwt.decode(token, key=secret, algorithms=["HS256"])
            return route_code(data)

        return route_code("Not authorization", 406)

    def put(self):
        req = reqparse.RequestParser()
        req.add_argument('password', required=True)
        args = req.parse_args()
        token = request.headers.get("authorization", None)
        user_info = User.query.filter(User.id == token['id']).first()
        user_info.password = args['password']
        db.session.commit()
        return jsonify({
            'code': 200,
            'msg': '密码修改成功'
        })


api.add_resource(UserView, '/v2/admin/register')
api.add_resource(UserLoginView, '/v2/admin/login')
api.add_resource(UserGetView, '/v2/admin/getUserInfo')
